import os
import time
import sys
import shutil

from egurmotorra import egurFuzz
from egurmutazio import fuzzCallback

class Egurra(object):
	
	def __init__(self):
		
		self.timeout = 2
		self.program = None
		self.crashes = 0
		self.iterations = 0
		self.factor = 10.0
		self.ext = None
	
	def fuzzCallback(self,buf):
		
		try:
			idatz = open("temp.%s" % self.ext,"w")
			idatz.write(buf)
			idatz.close()
		except IOError:
			print "[*] failed creating temporary file, skipping iteration"
			return
		
		self.iterations += 1
		
		input = os.getcwd()
		input += "\\temp.%s" % self.ext
		dbg = egurFuzz(self.timeout)
		dbg.load(self.program,"\"" + input + "\"")
		dbg.run()

		if len(dbg.info) > 0:
			self.crashes += 1
			dbg.print_info()
			time.sleep(1)
			data = time.localtime(time.time())
			data = "%d.%d.%d-%d.%d.%d" % (data.tm_year,data.tm_mon,data.tm_mday,data.tm_hour,data.tm_min,data.tm_sec)
			shutil.copy("temp.%s" % self.ext,"crashes\\crash-%d-%s.%s" % (self.crashes,data,self.ext))
			f = open("crashes\\crash-%d-%s.txt" % (self.crashes,data), "wb")
			f.write(os.linesep.join(dbg.info))
			f.close()
		
		print "[*] Iteration %d over, total of %d crashes so far." % (self.iterations,self.crashes)
	
	def fuzz(self):
		
		fuzzCallback(self.fuzzCallback,self.factor)

def usage():
	
	print "Usage: ", sys.argv[0], "<timeout> <program> <extension> <fuzz factor>"
	
def main(timeout, prog, ext, factor):
	
	print "\n\n[*] egurra 0.1 starting...\n\n"
	fuzzer = Egurra()
	fuzzer.program = prog
	fuzzer.timeout = int(timeout)
	fuzzer.ext = ext
	fuzzer.factor = float(factor)
	fuzzer.fuzz()
	
if __name__ == "__main__":
	if len(sys.argv) < 5:
		usage()
	else:
		main(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4])